<template>
    <div>
        <!-- 导航条 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card class="box-card"> 
            <el-row :gutter="20">
                <el-col :span="7">   
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" @clear="getUserList" clearable>
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="7">
                    <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 用户列表区域 -->
            <el-table :data="usersList" border stripe>
                <el-table-column type="index"></el-table-column>
                <el-table-column label="姓名" prop="username"></el-table-column>
                <el-table-column label="邮箱" prop="email"></el-table-column>
                <el-table-column label="电话" prop="mobile"></el-table-column>
                <el-table-column label="角色" prop="role_name"></el-table-column>
                <el-table-column label="状态" >
                  <template slot-scope="scope">  
                    <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
                    </el-switch> 
                  </template>  
                </el-table-column>
                <el-table-column label="操作" width="180px">
                    <template slot-scope="scope">
                    <el-button type="primary" icon="el-icon-edit" size="mini" @click="modifyUsers(scope.row.id)"></el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>                    
                    <el-tooltip :enterable="false" class="item" effect="dark" content="分配角色" placement="top">
                    <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRole(scope.row)"></el-button>
                    </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <!-- //分页区域 -->
            <div class="block">
                <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 5, 10]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="parseInt(total)">
                </el-pagination>
            </div>

            <!-- 添加用户的对话框 -->
            <el-dialog
            title="添加新用户"
            :visible.sync="addDialogVisible"
            width="50%" @close="addDialogClosed"           
            >
            <!-- 文本主题区域 -->
            <el-form :model="addForm" status-icon :rules="addFormRules" ref="addFormRef" label-width="70px" >
            <el-form-item label="用户名" prop="username">
                <el-input type="text" v-model="addForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="addForm.password" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input type="text" v-model="addForm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input type="text" v-model="addForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUsers">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 修改用户信息对话框 -->
             <el-dialog
            title="修改用户信息"
            :visible.sync="modifyDialogVisible"
            width="50%"
            @close="modifyDialogClosed"           
            >
            <!-- 文本主题区域 -->
            <el-form :model="modifyForm" status-icon :rules="modifyFormRules" ref="modifyFormRef" label-width="70px" >
            <el-form-item label="用户名">
                <el-input type="text" disabled v-model="modifyForm.username" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input type="text" v-model="modifyForm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="mobile">
                <el-input type="text" v-model="modifyForm.mobile" autocomplete="off"></el-input>
            </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="modifyDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="modifyUserInfo">确 定</el-button>
            </span>
            </el-dialog>

            <!-- 分配角色对话框 -->
            <el-dialog
            title="分配角色"
            :visible.sync="setRoleDialogVisible"
            width="50%"
            @close="setRoleClosed"       
            >
            <!-- 文本主题区域 -->
            <div>
                <p>当前的用户：{{userInfo.username}}</p>
                <p>当前的角色：{{userInfo.role_name}}</p>
               <p>
                   分配新角色：<el-select v-model="selectRoleid" placeholder="请选择">
                    <el-option
                    v-for="item in rolesList"
                    :key="item.id"
                    :label="item.roleName"
                    :value="item.id">
                    </el-option>
                    </el-select>
                </p> 
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRoleDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sureSetRole">确 定</el-button>
            </span>
            </el-dialog>


        </el-card>
    </div>
</template>

<script>
export default {
    data () {
        //这是element ui的表单自定义验证规则
        var checkEmail = (rule,value,callback) => {
            const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
            if(regEmail.test(value)){
                //合法的邮箱
                return callback()
            }
            callback(new Error('请输入合法的邮箱'))
        }
        var checkPhone = (rule,value,callback) => {
            const  phoneReg = /^1[3-578]\d{9}$/
            if(phoneReg.test(value)){
                //手机合法
                return callback()
            }
            callback(new Error('请输入正确的手机号码'))
        }
        return {
            //选中角色信息
            selectRoleid: '',
            //分配角色面板用户信息
            userInfo:{},
            //角色列表信息
            rolesList: [],
            setRoleDialogVisible: false,
            //获取用户列表的参数对象
            queryInfo: {
                query: '',
                //当前的页数
                pagenum: 1,
                //当前每页显示多少条数据
                pagesize: 2
            },
            //存放获取的数据
            usersList: [],
            total: 0,
            //控制添加用户对话框的显示与隐藏
            addDialogVisible: false,
            //修改用户的对话框的显示与隐藏
            modifyDialogVisible: false,
            //存放要修改的用户数据信息
            modifyForm: {},
            addForm: {
                username: '',
                password: '',
                email: '',
                mobile: ''
            },
            addFormRules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 10, message: '长度在 6 到 10 个字符', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur'}
                ],
                mobile: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }
                ]
            },
            modifyFormRules: {
                email: [
                    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur'}
                ],
                mobile: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { validator: checkPhone, trigger: 'blur' }
                ]
            }
            
        };
    },
    created () {
        this.getUserList() 
    },
    methods: {

       async getUserList () {
            const {data: res} = await this.$http.get('users', {params: this.queryInfo})
            if(res.meta.status !==200){
               return this.$message.error('获取用户列表失败')
            } 
            this.usersList = res.data.users
            this.total = res.data.total
            
        },
        //监听pagesize改变的事件
        handleSizeChange (newSize) {
            this.queryInfo.pagesize = newSize
            this.getUserList()
        },
        //监听页码改变的事件
        handleCurrentChange (newPage) {
            this.queryInfo.pagenum = newPage
            this.getUserList()
        },
        //监听状态开关
        async userStateChange (userinfo) {
            const {data: res} = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
            if(res.meta.status !== 200){
                userinfo.mg_state = !userinfo.mg_state
                return this.$message.error('更新用户状态失败')
                }
                this.$message.success('更新状态成功')
        },
        // 搜索输入框为空时自动显示全部数据
        // inputChange () {
        //     if(this.queryInfo.query == ''){
        //         this.getUserList()
        //     }
        // }

        //监听清空表单数据
        //resetFields()清空表单事件
        addDialogClosed () {
            this.$refs.addFormRef.resetFields()
        },
        //点击按钮，添加新用户
        addUsers () {
            this.$refs.addFormRef.validate(async valid => {
                if(!valid) return 
                //验证通过，发起添加请求
               const {data: res} = await this.$http.post('users',this.addForm)
               if(res.meta.status !== 201){
                   this.$message.error('添加用户失败')
               }
               this.$message.success('添加用户成功')

               //添加成功后关闭面板
               this.addDialogVisible = false
               //添加成功后重新加载数据
               this.getUserList()
            })
        },
        //点击按钮，修改用户信息
        async modifyUsers (id) {
            this.modifyDialogVisible = true
            const {data: res} = await this.$http.get('users/'+ id)
            if(res.meta.status !== 200 ) return this.$message.error('查询用户信息失败')
            this.modifyForm = res.data
        },
        //关闭面板，清空修改用户信息
        modifyDialogClosed () {
            this.$refs.modifyFormRef.resetFields()
        },
        //验证修改信息并发起修改请求
         modifyUserInfo () {
            this.$refs.modifyFormRef.validate(async valid =>{
                if(!valid) return 
                const {data: res} = await this.$http.put('users/'+this.modifyForm.id, {
                    email: this.modifyForm.email,
                    mobile: this.modifyForm.mobile
                })
                if(res.meta.status !== 200) return this.$message.error('修改失败')
                 this.$message.success('更新用户信息成功')
                 this.getUserList()
                 this.modifyDialogVisible = false
            })
        },
        //根据id删除用户信息
        // .then(result=>{
        //         if(result == 'confirm'){
        //             console.log('确认删除')
        //         }
        //     })
        async removeUserById (id) {
            //先弹框提示用户确认 
             const confirmResult = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err => err)//.catch()捕获错误信息并返回

            if(confirmResult !== 'confirm'){
               return this.$message.info('已经取消了删除') 
            }
            //确认删除执行的操作
            this.$http.delete('users/'+id).then(result=>{
                
                if(result.status !==200){
                    return this.$message.error('删除用户信息失败')
                }
                this.$message.success('删除用户信息成功')

                this.getUserList()
            })
        },

        //分配角色功能
        async showSetRole (role) {
            this.userInfo = role
            //获取所有的角色列表
          const {data: res} = await this.$http.get('roles')
          if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
          this.rolesList = res.data       
            this.setRoleDialogVisible = true
        },
        async sureSetRole () {
            if(!this.selectRoleid) return this.$message.info('请选择新的角色')
            //如果选择框里面有值，则发起请求
            const {data: res} = await this.$http.put(`users/${this.userInfo.id}/role`,{
                rid:this.selectRoleid
            })
            if(res.meta.status !== 200) return this.$message.error('分配角色失败')
            this.$message.success('分配角色成功')
            
            this.getUserList()

            this.setRoleDialogVisible = false

        },
        setRoleClosed () {
            this.selectRoleid = ''
        }
       
        },
};
</script>

<style scoped lang="scss">

</style>
